package com.samsungmobile.common_module;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.samsungmobile.common.Logger;
import com.samsungmobile.common.channel.ServletManager;
import com.samsungmobile.common.email.EmailCheck;
import com.samsungmobile.common.mail.MailSender;
import com.samsungmobile.common.util.EasyFile;
import com.samsungmobile.common.util.EasyString;
import com.samsungmobile.common_module.Exception.CommonModuleException;
import com.samsungmobile.security.UKDESEncryptDecrypt;


/**
 * @author Jinwoo
 *
 */
public class FormattedEmailSend extends ServletManager {
	
	//Parameter Values
	private String spCountry_Cd				= "";
	private String spLang_Cd 				= "";
	private String spTemplate				= "";
	private String spTitle					= "";
	private String spEmail_Address			= "";
	private String spSec_Key 				= "";
	private LinkedList<Properties> llpKey_Word = new LinkedList<Properties>();
	private LinkedList<Properties> llpEKey_Word = new LinkedList<Properties>();
	
	private String sEmail_Sender_Address	= "newsletter@samsungmobile.com"; 
	
	//Return Values
	private final String[] safSUCCESS 						= {"0","SUCCESS"};
	
	private final String[] safEMPTY_COUNTRY_CD				= {"101","EMPTY_COUNTRY_CD"};
	private final String[] safEMPTY_LANG_CD 				= {"102","EMPTY_LANG_CD"};
	private final String[] safEMPTY_TEMPLATE 				= {"103","EMPTY_TEMPLATE"};
	private final String[] safEMPTY_TITLE 					= {"104","EMPTY_TITLE"};
	private final String[] safEMPTY_EMAIL_ADDRESS 			= {"105","EMPTY_EMAIL_ADDRESS"};
	private final String[] safEMPTY_SEC_KEY 				= {"106","EMPTY_SEC_KEY"};
	
	private final String[] safINVALID_COUNTRY_CD 			= {"201","INVALID_COUNTRY_CD"};
	private final String[] safINVALID_LANG_CD 				= {"202","INVALID_LANG_CD"};
	private final String[] safINVALID_TEMPLATE 				= {"203", "INVALID_TEMPLATE"};
	private final String[] safINVALID_TITLE 				= {"204", "INVALID_TITLE"};
	private final String[] safINVALID_EMAIL_ADDRESS 		= {"205", "INVALID_EMAIL_ADDRESS"};
	private final String[] safINVALID_SEC_KEY 				= {"206", "INVALID_SEC_KEY"};
	
	private final String[] safAPI_INTERNAL_ERROR 			= {"500", "API_INTERNAL_ERROR"};
	private final String[] safAPI_AUTHORIZATION_ERROR 		= {"501", "API_AUTHORIZATION_ERROR"};

	private UKDESEncryptDecrypt ukdes = new UKDESEncryptDecrypt();
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void process() throws Exception {

		PrintWriter out = res.getWriter();
		HashMap<String,String> hm = new HashMap<String,String>();
		
		try{
			res.setContentType("text/xml; charset=UTF-8");
			
			setParams(req);
			
			checkValidation();
			
			SendMail();
			
			hm.put("RESULT_CODE", safSUCCESS[0]);
			hm.put("RESULT_MESSAGE", safSUCCESS[1]);
			
		} catch (CommonModuleException e) {
			
			Logger.LOG_NOHUP.error(e);
			hm.put("RESULT_CODE", e.getMessages()[0]);
			hm.put("RESULT_MESSAGE", e.getMessages()[1]);
		
		} catch (Exception e) {
			Logger.LOG_NOHUP.error(e);
			hm.put("RESULT_CODE", safAPI_INTERNAL_ERROR[0]);
			hm.put("RESULT_MESSAGE", safAPI_INTERNAL_ERROR[1]);
			e.printStackTrace();
		
		} finally {
			responseReturnXml(out, hm);
			
		}

	}

    /**
     * @param hm
     * @throws Exception
     */
    public void SendMail() throws Exception{
    	
    	String sMail_templete = "";
    	StringBuffer sbPath_file = new StringBuffer();
    	
    	sbPath_file.append("/home01/sm3/webapps/promo/prm/WEB-INF/mailform");
    	sbPath_file.append("/"+spCountry_Cd);
    	sbPath_file.append("/"+spLang_Cd);
    	sbPath_file.append("/"+spTemplate+".jsp");

        sMail_templete = EasyFile.readFile(sbPath_file.toString(), "UTF-8");
        
        for(int iLoop = 0 ; iLoop < llpKey_Word.size(); iLoop++){
        	sMail_templete = EasyString.replace(sMail_templete
        										, llpKey_Word.get(iLoop).getProperty("KEY")
        										, llpKey_Word.get(iLoop).getProperty("VALUE"));
        }

        for(int iLoop = 0 ; iLoop < llpEKey_Word.size(); iLoop++){
        	sMail_templete = EasyString.replace(sMail_templete
        										, llpEKey_Word.get(iLoop).getProperty("KEY")
        										, llpEKey_Word.get(iLoop).getProperty("VALUE"));
        }
        
    	MailSender.send(sEmail_Sender_Address, spEmail_Address, spTitle, sMail_templete);
 
    }	
		
	/**
	 * @param out
	 * @param hmResult
	 */
	private void responseReturnXml ( PrintWriter out, HashMap<String,String> hmResult ){

		StringBuffer sbReturn = new StringBuffer();
		
		sbReturn.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		sbReturn.append("<result>\n");
		sbReturn.append("	<responseCode>").append(hmResult.get("RESULT_CODE")).append("</responseCode>\n");
		sbReturn.append("	<responseMessage>").append(hmResult.get("RESULT_MESSAGE")).append("</responseMessage >\n");
		sbReturn.append("</result>");
		
		out.println(sbReturn);
	}	

	
	/**
	 * @param request
	 */
	private void setParams(HttpServletRequest request) throws Exception{

		request.setCharacterEncoding("UTF-8");
		
		spCountry_Cd 	= EasyString.toString(request.getParameter("country_cd")).trim().toLowerCase();
		spLang_Cd 		= EasyString.toString(request.getParameter("lang_cd")).trim().toUpperCase();
		spTemplate 		= EasyString.toString(request.getParameter("template")).trim().toLowerCase();
		spTitle 		= EasyString.toString(request.getParameter("title")).trim();
		
		spEmail_Address = EasyString.toString(request.getParameter("email_address")).trim();
		spEmail_Address = ukdes.decrypt(spEmail_Address);
		
		spSec_Key 		= EasyString.toString(request.getParameter("sec_key")).trim();
		spSec_Key		= ukdes.decrypt(spSec_Key);
		
		String sParamName = "";
		for(Enumeration e = request.getParameterNames();e.hasMoreElements(); ){
			sParamName = (String)e.nextElement();
			if( sParamName.startsWith("rp_") ){
				
				Properties p=new Properties();
				p.setProperty("KEY", "##"+sParamName.substring(3).toUpperCase()+"##");
				p.setProperty("VALUE", EasyString.toString(request.getParameter(sParamName)).trim());
				llpKey_Word.add(p);
				
			}else if( sParamName.startsWith("erp_") ){
				
				Properties p=new Properties();
				
				String sValue = EasyString.toString(request.getParameter(sParamName)).trim();
				sValue = ukdes.decrypt(sValue);
				
				p.setProperty("KEY", "##"+sParamName.substring(4).toUpperCase()+"##");
				p.setProperty("VALUE", sValue);
				llpEKey_Word.add(p);
			}
		}
		
		if(spTemplate.equals("tellafriend")){
			sEmail_Sender_Address = "tellafriend@samsungmobile.com";
		}
	}
	
	/**
	 * @param response
	 * @param out
	 * @throws Exception
	 */
	private void checkValidation() throws Exception{
	
		EmailCheck ec = new EmailCheck();
		
		if(spCountry_Cd.equals("")){
			throw new CommonModuleException(safEMPTY_COUNTRY_CD);
			
		}else if(spCountry_Cd.length() != 3){
			throw new CommonModuleException(safINVALID_COUNTRY_CD);
			
		}else if(spLang_Cd.equals("")){
			throw new CommonModuleException(safEMPTY_LANG_CD);
			
		}else if(spLang_Cd.length() != 3){
			throw new CommonModuleException(safINVALID_LANG_CD);

		}else if(spTemplate.equals("")){	
			throw new CommonModuleException(safEMPTY_TEMPLATE);
			
		}else if(!spTemplate.matches("^(welcome_phone|welcome_nophone|confirm_email|forgot_password|tellafriend)$")){
			throw new CommonModuleException(safINVALID_TEMPLATE);
			
		}else if(spTitle.equals("")){
			throw new CommonModuleException(safEMPTY_TITLE);
			
		}else if(spTitle.length() > 200){
			throw new CommonModuleException(safINVALID_TITLE);

		}else if(spSec_Key.equals("")){
			throw new CommonModuleException(safEMPTY_SEC_KEY);
			
		}else if(spSec_Key.equals("*********************")){
			throw new CommonModuleException(safINVALID_SEC_KEY);
			

		}else if(!spSec_Key.substring(16).equals(spEmail_Address)){
			throw new CommonModuleException(safAPI_AUTHORIZATION_ERROR);
			
		}
		
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:HH:mm");

		Date paramDate = (Date)formatter.parse(spSec_Key.substring(0, 16));
		Date rightNow = new Date();		
		
		if(paramDate.after(rightNow) || paramDate.getTime() < rightNow.getTime() - 10*60*1000){
	
			throw new CommonModuleException(safAPI_AUTHORIZATION_ERROR);
			
		}else if(spEmail_Address.equals("")){
			throw new CommonModuleException(safEMPTY_EMAIL_ADDRESS);
			
		}else if(!isEmail(spEmail_Address)){
			throw new CommonModuleException(safINVALID_EMAIL_ADDRESS);
			
		//Put this validation at the last.
		//because that make DNS transaction that cause network traffic and take some time to get a respond
		}else if(!(ec.CheckEmailServer(spEmail_Address)) ){
			throw new CommonModuleException(safINVALID_EMAIL_ADDRESS);

		}

	}
	
	/**
	 * @param sEmail
	 * @return
	 */
	private static boolean isEmail(String sEmail) {
        if (sEmail==null) return false;
        boolean bRtn = Pattern.matches("[\\w\\~\\-\\.]+@[\\w\\~\\-]+(\\.[\\w\\~\\-]+)+", sEmail.trim());
        return bRtn;
    }
}
	